// pages/device/privilegeDetail/privilegeDetail.js
import lwx from '../../../utils/lwx.js'
import {
  _globle
} from '../../../utils/globle.js'
import devices from '../../../utils/devices.js'
Page({
  _useId: 5,
  rand2: 0,
  rand1: 0,
  /**
   * 页面的初始数据
   */
  data: {

    detail: {},
    isUse: false,
    showMask: false,
    devicesActId: '',
    devicesTakeId: '',
    applyInfo: ["../../../images/add_photo.jpg"],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.loadData(options);
    this.openBt();
  },
  openBt() {
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter({
        success: function(res) {

        },
        fail: function(err) {
          wx.showToast({
            title: '请开启蓝牙',
            icon: 'none',
            duration: 1000
          })
          setTimeout(() => {
            wx.navigateBack({})
          }, 1000)
        }
      })
    } else {
      wx.showToast({
        title: '请开启蓝牙',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        wx.navigateBack({})
      }, 1000)
    }
  },
  loadData: function(options) {
    var that = this;
    lwx.request({
      url: "privileged.people.info",
      data: {
        sealId: options.sealId,
        companyId: _globle.user.companyId
      }
    }).then(res => {
      if (res.data.code == '0') {
        this.setData({
          detail: res.data.privilegedUse
        })
      } else {
        wx.showToast({
          title: res.data.message,
        })
      }
    }).catch(err => {
      console.log('err' + err);
    })
  },
  lockStateUpdate: function() {
    if (!this._devices) {
      this._devices = new devices(this.data.detail.devicesCode)
    }
    wx.hideLoading()
    wx.showLoading({
      title: '读取状态...',
      mask: true
    })
    this._devices.getOperationStatus().then(res => {
      if (res.operationStatus === 2) {
        wx.hideLoading()
        wx.showLoading({
          title: '解除锁定',
          mask: true
        })
        this._devices.setOperationCommand({
          type: 3,
          sign: this.data.detail.sign,
          rand1: res.rand1,
          rand2: res.rand2
        }).then(res => {
          return new Promise((resolve, reject) => {
            wx.hideLoading()
            wx.showLoading({
              title: '获取结果...',
              mask: true
            })
            // 循环读取状态
            let statusInterval = setInterval(() => {
              this._devices.getOperationStatus().then(res => {
                // 空闲则是安装完成
                if (res.operationStatus !== 1) {
                  clearInterval(statusInterval)
                  resolve(res.operationStatus)
                }
              })
            }, 100)
          })
        }).then(res => {
          wx.hideLoading()
          if (res === 2) {
            wx.showToast({
              title: '解除错误锁定失败',
              mask: true,
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: '解除成功',
              mask: true
            })
            // this.nextStep()
          }
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
          wx.showToast({
            title: '解除操作失败',
            mask: true,
            icon: 'none'
          })
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '设备正常，无错误信息',
          mask: true,
          icon: 'none'
        })
      }
    }).catch(res => {
      wx.hideLoading()
      wx.showToast({
        title: '获取运行状态失败',
        mask: true,
        icon: 'none'
      })
    })
  },
  upInstall: function() {
    if (this._devices) {
      console.log('断开连接')
      this._devices.closeConnection()
    }
    // let currentVersion = `${this.data.devicesInfo.majorVersion}.${this.data.devicesInfo.subVersion}.${this.data.devicesInfo.minorVersion}`
    let currentVersion = '0.0.0'
    wx.navigateTo({
      url: `../ota/index/index?deviceCode=${this.data.detail.devicesCode}&currentVersion=${currentVersion}&version=${this._version}&path=${this._path}&deviceId=${this.data.detail.devicesId}&sign=${this.data.detail.sign}`,
    })
  },

  use: function() {
    var that = this
    if (!that._devices) {
      that._devices = new devices(that.data.detail.devicesCode)
    }
    let errMsg = '使用失败'
    that._devices.getOperationStatus().then(res => {
      return new Promise((resolve, reject) => {
        console.log(res)
        if (res.operationStatus === 0) {
          that.rand1 = res.rand1
          that.rand2 = res.rand2
          resolve(res.operationStatus)
        } else if (res.operationStatus === 1) {
          reject('设备繁忙,请稍后再试')
        } else {
          resolve(res.operationStatus)
          reject('设备已锁定，请先到设备详情解锁')
        }
      })
    }).then(res => {
      wx.hideLoading()
      wx.showLoading({
        title: '使用印章',
        mask: true
      })
      return lwx.request({
        url: 'privileged.people.enable',
        data: {
          devicesId: that.data.detail.devicesId,
          totalTimes: 1,
          sealId: that.data.detail.sealId
        }
      })
    }).then(res => {
      that._usedId = res.data.useId
      console.log('useId======' + res.data.useId)
      wx.hideLoading()
      wx.showLoading({
        title: '解锁设备...',
        mask: true
      })
      // 使用设备
      return that._devices.setOperationCommand({
        type: 2,
        sign: that.data.detail.sign,
        rand1: that.rand1,
        rand2: that.rand2
      })
    }).then(res => {
      return new Promise((resolve, reject) => {
        console.log('进入获取状态')
        let devicesStatus = 0
        let msg = '获取状态...'
        wx.hideLoading()
        wx.showLoading({
          title: msg,
          mask: true
        })
        let handler = () => {
          this._devices.getOperationStatus().then(res => {
            console.log('要敲章了=====' + JSON.stringify(res))
            if (res.operationStatus == 1) {
              if (res.devicesStatus != devicesStatus) {
                devicesStatus = res.devicesStatus
                console.log('devicesStatus' + devicesStatus)
                switch (devicesStatus) {
                  case 2:
                    msg = '正在敲章';
                    break
                  case 11:
                    msg = '印章已按下';
                    break
                  case 12:
                    msg = '印章已返回';
                    break
                }
                wx.hideLoading()
                wx.showLoading({
                  title: msg,
                  mask: true
                })
              }
              setTimeout(handler, 100)
            } else {
              resolve(res.operationStatus)
            }
          })
        }
        setTimeout(handler, 100)
      })
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res === 0) {
        this.useSuccess()
      } else {
        this.useError()
      }
    }).catch(err => {
      console.log(err)
      errMsg = typeof err === 'string' ? err : errMsg
      wx.showToast({
        title: errMsg,
        mask: true,
        icon: 'none'
      })
    })
  },
  useSuccess: function() {
    setTimeout(function() {
      wx.showToast({
        title: '用章完成',
        mask: true
      })
    }, 1000)

    // this.nextStep()
  },
  useError: function() {
    if (!this._devices) {
      this._devices = new devices(this._deviceCode)
    }
    this._devices.getErrorInfo().then(res => {

      let times = null
      if (res.errorType == 4) {
        times = res.errorData
      }
      let errMsg = res.mes
      // lwx.request({
      //   url: '/use/rollback',
      //   data: {
      //     actId: this._actId,
      //     latitude: _globle.location.latitude || '',
      //     longitude: _globle.location.longitude || '',
      //     cause: errMsg ? errMsg : '其他原因',
      //     times: times || ''
      //   }
      // }).then(res => {
      //   console.log('记录使用失败成功')
      // }).catch(err => {
      //   console.log('记录使用失败失败')
      // })

      wx.showModal({
        title: '使用失败',
        content: (errMsg ? ('使用失败【' + errMsg + '】') : '') + '设备锁定' + ',解锁设备?',
        cancelText: '取消',
        confirmText: '解锁',
        success: res => {
          if (res.confirm) {
            this.releaseError()
          } else {
            wx.showToast({
              title: '请到设备详情解锁设备才能继续使用',
              mask: true,
              icon: 'none'
            })
          }
        }
      })
    }).catch(err => {
      wx.showModal({
        title: '使用失败',
        content: '使用失败【原因未知】设备锁定,解锁设备?',
        cancelText: '取消',
        confirmText: '解锁',
        success: res => {
          if (res.confirm) {
            this.releaseError()
          } else {
            wx.showToast({
              title: '请到设备详情解锁设备才能继续使用',
              mask: true,
              icon: 'none'
            })
          }
        }
      })
    })
  },
  releaseError: function() {

    if (!this._devices) {
      this._devices = new devices(this.data.detail.devicesCode)
    }
    wx.hideLoading()
    wx.showLoading({
      title: '读取状态...',
      mask: true
    })

    this._devices.getOperationStatus().then(res => {
      if (res.operationStatus === 2) {
        wx.hideLoading()
        wx.showLoading({
          title: '解除锁定',
          mask: true
        })
        this._devices.setOperationCommand({
          type: 3,
          sign: this.data.detail.sign,
          rand1: res.rand1,
          rand2: res.rand2
        }).then(res => {
          return new Promise((resolve, reject) => {
            wx.hideLoading()
            wx.showLoading({
              title: '获取结果...',
              mask: true
            })
            // 循环读取状态
            let statusInterval = setInterval(() => {
              this._devices.getOperationStatus().then(res => {
                // 空闲则是安装完成
                if (res.operationStatus !== 1) {
                  clearInterval(statusInterval)
                  resolve(res.operationStatus)
                }
              })
            }, 100)
          })
        }).then(res => {
          wx.hideLoading()
          if (res === 2) {
            wx.showToast({
              title: '解除错误锁定失败',
              mask: true,
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: '解除成功',
              mask: true
            })
            // this.nextStep()
          }
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
          wx.showToast({
            title: '解除操作失败',
            mask: true,
            icon: 'none'
          })
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '设备正常，无错误信息',
          mask: true,
          icon: 'none'
        })
      }
    }).catch(res => {
      wx.hideLoading()
      wx.showToast({
        title: '获取运行状态失败',
        mask: true,
        icon: 'none'
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  deletePerson: function() {
    wx.showModal({
      title: '暂未开放此功能',
      content: '',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    if (this._devices) {
      console.log('断开连接')
      this._devices.closeConnection()
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    if (this._devices) {
      console.log('断开连接')
      this._devices.closeConnection()
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})